package cn.wit.summit.chwan.task;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;

import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.tools.downloadtool.DownloadFactory;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.CompressOperate_zip4j;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.utils.XZip;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by lala on 15/5/9.
 */
public class UNAndroidZIPThread extends Thread implements IZIPThread {
    private Context context;
    private DownLoadTaskTable mDownLoadTaskTable;
    public boolean running = true;
    public boolean isTransfer = false;
    ProgressMonitor progressMonitor = null;

    public UNAndroidZIPThread(DownLoadTaskTable DownLoadTaskTable, Context context) {
        this.mDownLoadTaskTable = DownLoadTaskTable;
        this.context = context;
    }

    public UNAndroidZIPThread(DownLoadTaskTable DownLoadTaskTable, Context mContext, boolean isTransfer) {
        this.mDownLoadTaskTable = DownLoadTaskTable;
        this.context = mContext;
        this.isTransfer = isTransfer;
    }

    @Override
    public void stopRunning() {
        running = false;
        progressMonitor.setMonitor(false);

    }

    @Override
    public boolean isRunning() {
        return running;
    }

    class ProgressMonitor extends Thread {
        private boolean monitor = true;
        File mFile;
        File fileApk = null;

        public ProgressMonitor(File file, File fileApk) {
            mFile = file;
            this.fileApk = fileApk;
        }

        @Override
        public void run() {
            super.run();
            try {
                while (monitor) {

                    long currentSize = UtilsMy.getDirSize(mFile);
                    long surrentApk = 0;
                    if (fileApk != null) {
                        surrentApk = fileApk.length();
                    }

                    Log.d("UNZIPThread", "zip currentSize =" + currentSize + "   surrentApk= " + surrentApk);
                    long totalSize = mDownLoadTaskTable.getUnzip_size();

                    if (totalSize == 0) {
                        totalSize = 1;
                    }
                    int zipProgress = (int) (100 * (currentSize + surrentApk) / totalSize);
                    LogUtils.e("tbl>>>zipProgress:"+zipProgress);
                    mDownLoadTaskTable.setDownprogress(zipProgress);
//                    DownloadService.updatezipProgress(mDownLoadTaskTable);
                    EventBus.getDefault().post(mDownLoadTaskTable.getDownEvent());


                    sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                stopRunning();
            }
        }

        public void setMonitor(boolean monitor) {
            this.monitor = monitor;
        }
    }

    @Override
    public void run() {
        super.run();
        Log.d("UNZIPThread", "UNZIPThread called.");
        long zipStartTime = System.currentTimeMillis();
        long zipEndTime;
        String speed = "0";

        String romsPath = null;
        if (StringUtils.isEmpty(mDownLoadTaskTable.getDownPath())){
            unError("解压文件为空");
            return;
        }
        File file = new File(mDownLoadTaskTable.getDownPath());
        String obbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/obb";
        String dataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data";
        try {
            try {
                boolean exists = file.exists();
                if (exists && StringUtils.isNotEmpty(mDownLoadTaskTable.getDownPath())) {
                    zipStartTime = System.currentTimeMillis();

                    String rootpath = null;
                    if (mDownLoadTaskTable.getGameType() == 1) {
                        rootpath = obbPath;
                    } else if (mDownLoadTaskTable.getGameType() == 2) {
                        rootpath = dataPath;
                    }

                    File fileroot = new File(rootpath);
                    if (!fileroot.exists()) {
                        fileroot.mkdirs();
                    }

//                    String apkPath = "";
//                    try {
//                        apkPath = XZip.getDPKRomPath(file, rootpath);
//                    } catch (Exception e) {
//                        apkPath = CompressOperate_zip4j.getDPKRomPath(file, rootpath);
//                    }
//
//                    progressMonitor = new ProgressMonitor(new File(rootpath + File.separator + mDownLoadTaskTable.getPackageName()), new File(apkPath));
//                    progressMonitor.start();

                    try {
                        romsPath = XZip.upZipDpkFile(this, file, rootpath);
                        if (StringUtils.isEmpty(romsPath)) {
                            romsPath = CompressOperate_zip4j.upZipDpkFile(this, file, rootpath);
                            if (StringUtils.isEmpty(romsPath)) {
                                unError("解压后没有找到apk文件");
                                return;
                            }
                        }
                    } catch (Exception e) {
                        romsPath = CompressOperate_zip4j.upZipDpkFile(this, file, rootpath);
                        if (StringUtils.isEmpty(romsPath)) {
                            unError("解压后没有找到apk文件");
                            return;
                        }
                    }

                    //设置解压出来的apk包路径用来安装完成后删除包
                    mDownLoadTaskTable.setDownPath(romsPath);
                    zipEndTime = System.currentTimeMillis();
                    long time = zipEndTime - zipStartTime;
                    try {
                        speed = UtilsMy.FormatFileSizeForSpeed(mDownLoadTaskTable.getTotalSize() / time);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    unError("文件不存在或者解压文件path为空");
                    return;
                }

            } catch (Exception e) {
                StringWriter sw = null;
                try {
                    sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw, true);
                    e.printStackTrace(pw);
                    pw.flush();
                    sw.flush();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                unError("解压失败  "+sw.toString());
                return;
            }

            if (progressMonitor != null)
                progressMonitor.setMonitor(false);

            if (!running) {
                return;//该任务已经废弃了
            }


            try {
                //如果解压出来返回的是空
                File apkRom = new File(romsPath);

                if (romsPath == null || "".equals(romsPath) || !apkRom.exists()) {
//                    mDownLoadTaskTable.setDownStatus(DownLoadStatusConfig.UNZIP_ERROR);
//
//                    DownloadEvent event = mDownLoadTaskTable.getDownEvent();
//                    DownloadTaskManager.getInstance().updateStatusBygameId(mDownLoadTaskTable.getGameId(), mDownLoadTaskTable.getDownStatus());
//                    EventBus.getDefault().post(event);
                    unError("解压出来文件目录为空或者文件不存在");
                    return;
                }


                UtilsMy.delete(file);
                mDownLoadTaskTable.setDownPath(romsPath);


                mDownLoadTaskTable.setDownprogress(100);
//                EventBus.getDefault().post(mDownLoadTaskTable.getDownEvent());

                StatFactory.getInstance().sendGameDownLoadDone(context, mDownLoadTaskTable.getGameId());
                mDownLoadTaskTable.setDownStatus(DownLoadStatusConfig.INSTALL_WAIT);
                try {
                    DownloadTaskManager.getInstance().updateStatusBygameId(mDownLoadTaskTable.getGameId(), DownLoadStatusConfig.INSTALL_WAIT);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                StatFactory.getInstance().sendUnZipSuccess(MyApplication.getMyApplication().getApplicationContext(), mDownLoadTaskTable.getGameId(), 1 + "", speed);
                EventBus.getDefault().post(mDownLoadTaskTable.getDownEvent());

                DownloadFactory.get().removeZipTask(mDownLoadTaskTable.getGameId());

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //先获取是否有安装未知来源应用的权限
                    boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                    haveInstallPermission = true;
                    if (haveInstallPermission) {
                        APKUtils.getInstance(context).installAPK(context, romsPath, mDownLoadTaskTable.getGameId());
                        return;
                    }
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    if (EasyPermissions.hasPermissions(context, Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
                        APKUtils.getInstance(context).installAPK(context, romsPath, mDownLoadTaskTable.getGameId());
                        return;
                    } else {

                    }
                } else {
                    APKUtils.getInstance(context).installAPK(context, romsPath, mDownLoadTaskTable.getGameId());
                    return;
                }
                Intent intent2 = new Intent();
                intent2.setAction(BroadcastAction.ACTION_INSTALL_OBB_DATA_APK);
                //要发送的内容
                intent2.putExtra("apkpath", romsPath);
                intent2.putExtra("apkGameId", mDownLoadTaskTable.getGameId());
                //发送 一个无序广播
                context.sendBroadcast(intent2);
            } catch (Exception e) {
                e.printStackTrace();
                StringWriter sw = null;
                try {
                    sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw, true);
                    e.printStackTrace(pw);
                    pw.flush();
                    sw.flush();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                unError("解压后处理逻辑异常  "+sw.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
            StringWriter sw = null;
            try {
                sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                e.printStackTrace(pw);
                pw.flush();
                sw.flush();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            unError("解压整体异常  "+sw.toString());
        } finally {
            DownloadFactory.get().removeZipTask(mDownLoadTaskTable.getGameId());
        }

    }

    private void unError(String  errorMessage) {
        try {
            if (progressMonitor != null) progressMonitor.setMonitor(false);


            if (!UtilsMy.isStorageSatisfied(context, mDownLoadTaskTable, true)) {
                //                    context.sendBroadcast(new Intent(BroadcastAction.ACTION_INSUFFICIENT_STORAGE));
            } else {

            }
            MyApplication.toastHandler.sendEmptyMessage(1);
            mDownLoadTaskTable.setDownStatus(DownLoadStatusConfig.UNZIP_ERROR);
            StatFactory.getInstance().sendUnZipError(MyApplication.getMyApplication().getApplicationContext(), mDownLoadTaskTable.getGameId(), 2 + "",errorMessage);
            DownloadEvent event = mDownLoadTaskTable.getDownEvent();
            event.setStatus(DownLoadStatusConfig.UNZIP_ERROR);
            DownloadTaskManager.getInstance().updateStatusBygameId(mDownLoadTaskTable.getGameId(), mDownLoadTaskTable.getDownStatus());
            EventBus.getDefault().post(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
